<template>
  <div class="dashboard-container"
    v-loading="loading"
    element-loading-text="拼命解析中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @dragover="fileDragover" @drop="fileDrop"
  >
    <!-- <div class="dashboard-text">name: {{ name }}</div> -->

    <div id="luckysheet" 
      class="luckysheet" :class="{
      'ifShow':ifShow
    }" style=""></div>
    
    <input type="text">
    <el-upload
      class="upload-demo"
      ref="upload" 
      drag
      :multiple='false'
      :auto-upload='false'
      :file-list="fileList"
      :limit="10"
      :before-remove="beforeRemove"
      :on-change="handleChange"
      action="https://jsonplaceholder.typicode.com/posts/"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传Excel文件</div>
    </el-upload>

    <!-- Table -->
    <div
      class="dialogTableVisible" 
    >
      <span @click="ifDialogShow">编译表格成lua</span>
      <span @click="openFile">上传文件(拖到这里也行)</span>
    </div>

    <el-dialog title="数据编译" :visible.sync="dialogTableVisible">
      <h1>1. 设置通用表里的 key (module[这里使用表格的那个值])</h1>

      <el-input v-model="input" @change="inputChange" placeholder="请输入列头数据依据"></el-input>

      <!-- <h1>2. 选择Excel文件 (请按照首页说明的格式)</h1> -->
        <!-- <input type="file" ref="inputUpload" accept=".xls,.xlsx" class="outputlist_upload"> <div @click="excelFile=null">清除</div> -->

      <br>
      <!-- <a href="https://tool.oschina.net/codeformat/json/">格式化</a> -->
      <br>
      <!-- {{htmlData}} -->
      <h1 v-if="excelFile">3. 选择Excel表单列表</h1>
      <!-- {{input}} {{show}} -->
      <div v-for="(i,index) in htmlData" class="excelTitle" :class="{
        'redText':show == i.id
      }"  :key="'01'+index" @click="show = i.id">
        <h4>{{i.wsname}}</h4> 
      </div>
      <!-- <h4>{{htmlData[index].wsname}}</h4> -->
      <div v-for="(i,index) in htmlData"  :key="'02'+index" v-show="show == i.id">
        <el-button class="tag-read" type="primary"  :data-clipboard-text="i.text" @click="copy">复制代码</el-button>
        <el-button @click="selectText(i.id)">全选代码</el-button>
        <!-- <h4 @click="cloneCode(i.text)">复制</h4> -->
        <!-- <prism-editor :code="i.text" language="js"></prism-editor> -->
        <div class="textarea_box" contenteditable = "true" :id="i.id" v-html="i.text" style="white-space: pre-wrap;"></div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import XLSX from 'xlsx'
import Clipboard from 'clipboard'
import LuckyExcel from 'luckyexcel'
// import PrismEditor from 'vue-prism-editor'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  components: {
    // PrismEditor
  },
  data(){
    return{
      excelSheets:{},

      dialogTableVisible:false,

      ifShow:false,
      show:'',
      input:'',
      textarea:'',
      htmlData:[],

      excelFile:null,
      fileList: [],
      loading:false
    }
  },
  mounted(){
    this.initLuckysheet()

    let upload = document.querySelector('.luckysheet');
    // upload.addEventListener('dragenter', this.onDrag, false);
    // upload.addEventListener('dragover', this.onDrag, false);
    console.log(' upload ',upload)
    // upload.addEventListener('dragenter', this.onDrag, false);
    // upload.addEventListener('dragover', this.onDrag2, false);
    // upload.addEventListener('drop', this.onDrop, false);
  },
  methods:{
    ifDialogShow(){
      this.dialogTableVisible = true
    },
    openFile(){
      // this.$refs.upload.clearFiles()
      this.$refs.upload.$children[0].handleClick();
    },
    // 拖拽上传
    fileDragover (e) {
      e.preventDefault()
      console.log('拖拽上传',e)
    },
    getfile(file){
      console.log(file)
      console.log(' ------------ 拖拽释放鼠标 ------------ ')
      // let readExcel = this.readExcel(file)
      let loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      console.log(' ------------ LuckyExcel ------------ ')
      // 先确保获取到了xlsx文件file，再使用全局方法window.LuckyExcel转化
      LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile)=>{
        // 获得转化后的表格数据后，使用luckysheet初始化，或者更新已有的luckysheet工作簿
        // 注：luckysheet需要引入依赖包和初始化表格容器才可以使用
        console.log(' exportJson ',exportJson)
        console.log(' luckysheetfile ',luckysheetfile)
        this.excelSheets = exportJson.sheets
        this.initLuckysheet({
            data:exportJson.sheets,
            title:exportJson.info.name,
            userInfo:exportJson.info.name.creator
        })
      });
    },
    fileDrop (e) {
      e.preventDefault()
      const file = e.dataTransfer.files[0] // 获取到第一个上传的文件对象
      this.getfile(file)
    },
    onDrag (e) {
      // console.log('1. onDrag e ',e)
      e.stopPropagation();
      e.preventDefault();
      this.ifShow = false
    },
    onDrag2 (e) {
      // console.log('2. onDrag e ',e)
      e.stopPropagation();
      e.preventDefault();
      this.ifShow = true
    },
    onDrop (e) {
      console.log('3. onDrop e ',e)
      e.stopPropagation();
      e.preventDefault();
      let file = e.dataTransfer.files[0]
      this.readExcel(e)

    },
    // 表格初始化
    initLuckysheet(obj){
      //luckysheet配置项
      var options = {
        container: 'luckysheet', //luckysheet为容器id
        title: '表格模板', // 设定表格名称
        lang: 'zh', // 设定表格语言
        ...obj
      }
      luckysheet.create(options)
      
      console.log(' 表格模板数据 ',luckysheet.getcellvalue())
    },
    handleChange(file, fileList) {
      console.log(' 选择文件 ',file, fileList)
      var event = event || window.event;
      this.fileList = [file]
      this.readExcel(file.raw);
      this.excelFile = file.raw
      this.getfile(file.raw)
    },
    beforeRemove(file, fileList) {
      console.log(' 移除文件 ',file, fileList)
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    copy () {
      var clipboard = new Clipboard('.tag-read')
      clipboard.on('success', e => {
          console.log('复制成功')
          this.$message({
            message: '已复制到剪切板，Ctrl + v去吧！！',
            type: 'success'
          });
          //  释放内存
        clipboard.destory()
      })
      clipboard.on('error', e =>{
        // 不支持复制
        console.log('该浏览器不支持复制')
        // 释放内存
        clipboard.destory()
      })
    },
    cloneCode(text){
              
      // const
      //   input = document.createElement(
      //     'input'
      //   );

      // document.body.appendChild(input);

      // input.setAttribute(
      //   'value'
      //   ,
      //   text
      // );

      // input.select();


      // if
      //   (document.execCommand(
      //     'copy'
      //   )) {

      //   document.execCommand(
      //     'copy'
      //   );


      //   this.$message({
      //     message: '已复制到剪切板，Ctrl + v去吧！！',
      //     type: 'success'
      //   });

      // }

      // document.body.removeChild(input);
            
    },

    inputChange(e){
        console.log(e)
        this.readExcel(this.excelFile);
        this.readExcel(this.excelFile);
    },
    selectText(element) {
        var text = document.getElementById(element);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
            /*if(selection.setBaseAndExtent){
                selection.setBaseAndExtent(text, 0, text, 1);
            }*/
        } else {
            alert("none");
        }
    },
    readExcel(e) {//表格导入
        this.loading = true
        var that = this;
        const files = [e] //-- e.target.files;
        console.log('表格',files);

        if(files.length<=0){//如果没有文件名
          return false;
        }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
          this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
          return false;
        }

        console.log('-- 内容 --');

        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            console.log(workbook)
            // this.initLuckysheet({
            //   data:workbook.Sheets,
            //   title:workbook.SheetsNames[0],
            // })

            // LuckyExcel.transformExcelToLucky(e, (exportJson, luckysheetfile)=>{
            //   // 获得转化后的表格数据后，使用luckysheet初始化，或者更新已有的luckysheet工作簿
            //   // 注：luckysheet需要引入依赖包和初始化表格容器才可以使用
            //   console.log(' exportJson ',exportJson)
            //   console.log(' luckysheetfile ',luckysheetfile)
            //   this.initLuckysheet({
            //       data:exportJson.sheets,
            //       title:exportJson.info.name,
            //       userInfo:exportJson.info.name.creator
            //   })
            // });


            // const wsname = workbook.SheetNames[0];//取第一张表
            // let [index,value] of [‘a’,‘b’,‘c’].entries()
            that.htmlData  = []
            for (const [index,value] of workbook.SheetNames.entries()) {
              let wsname = value
              console.log('表格',index,value)
              const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
              console.log('表格内容 ',ws);

              that.htmlData[index] = {}
              that.htmlData[index].id = 'id_' + index
              that.htmlData[index].wsname = wsname
              that.htmlData[index].text = 
`local module = {}

	module['注释'] = 
				${JSON.stringify(ws[0])}
              `
              for (let i = 1; i < ws.length; i++) {
                const element = ws[i];
                
                that.htmlData[index].text += `
	module[${that.input?"'"+element[that.input]+"'":i}] = 
				${JSON.stringify(element)}
                `
              }
              // 特殊样式不要更改
              that.htmlData[index].text += `
return module`

              // console.log('插入数据',JSON.stringify(obj));
            //  {"
              that.htmlData[index].text = that.htmlData[index].text.replace(/:/g,"=").replace(/{"/g,"{").replace(/,"/g,",").replace(/"=/g,"=")
              console.log('显示内容',that.htmlData[index].text)
            }
            console.log('输出信息',that.htmlData)
            that.show = that.htmlData[0].id
            
            this.loading = false
            // that.outputs = [];//清空接收数据
            // for(var i= 0;i<ws.length;i++){
            // var sheetData = {
            //     address: ws[i].addr,
            //     value: ws[i].value
            // }
            // that.outputs.push(sheetData);
            // }
            // this.$refs.upload.value = '';
 
           
        };
        // fileReader.readAsBinaryString(files[0]);
        fileReader.readAsArrayBuffer(files[0]);
    },

  }
}
</script>

<style >
</style>
<style lang="scss" scoped>
  .el-dialog__wrapper{
    z-index: 1000000000000000000!important;
  }
  .v-modal{
    z-index: 100000000!important;
  }
  .dialogTableVisible{
    color: cornflowerblue;
    width: 300px;
    line-height: 40px;
    background-color: #fff;
    position: absolute;
    top: 10px;
    right: 0px;
    z-index: 100;

    display: flex;
    justify-content: space-around;
  }
  .ifShow{
    border: 1px solid #a7a6a6;
  }
  .dashboard-container{
    margin: 0!important;
  }
  #luckysheet{
    z-index: 100;

    width:100vw;
    height:100vh;
    // left: 0px;
    // top: 0px;
    background-color: #a7a6a6;
  }
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.excelTitle{
  color:cadetblue;
}
.redText{
  color: rebeccapurple;
}
</style>
